const { query } = require('../config/database');

class NotificationService {
  constructor(io, userSockets) {
    this.io = io;
    this.userSockets = userSockets;
  }

  // 发送实时通知
  async sendNotification(userId, notification) {
    try {
      // 保存通知到数据库
      const result = await query(
        'INSERT INTO notifications (user_id, title, content, summary, type, is_read) VALUES (?, ?, ?, ?, ?, FALSE)',
        [userId, notification.title, notification.content, notification.summary, notification.type]
      );

      const notificationId = result.insertId;
      const fullNotification = {
        id: notificationId,
        ...notification,
        is_read: false,
        created_at: new Date().toISOString()
      };

      // 通过WebSocket发送给用户
      const userSocket = this.userSockets.get(userId);
      if (userSocket) {
        userSocket.emit('new_notification', fullNotification);
        console.log(`实时通知已发送给用户 ${userId}:`, fullNotification.title);
        return { success: true, notification: fullNotification };
      } else {
        console.log(`用户 ${userId} 未在线，通知已保存到数据库`);
        return { success: true, notification: fullNotification, offline: true };
      }
    } catch (error) {
      console.error('发送通知失败:', error);
      throw error;
    }
  }

  // 广播系统通知
  async broadcastSystemNotification(notification) {
    try {
      // 获取所有在线用户
      const onlineUserIds = Array.from(this.userSockets.keys());
      
      if (onlineUserIds.length === 0) {
        console.log('没有在线用户，跳过广播');
        return { success: true, message: '没有在线用户' };
      }

      // 为每个在线用户创建通知
      const promises = onlineUserIds.map(userId => 
        this.sendNotification(userId, notification)
      );

      await Promise.all(promises);
      console.log(`系统通知已广播给 ${onlineUserIds.length} 个用户`);
      return { success: true, count: onlineUserIds.length };
    } catch (error) {
      console.error('广播系统通知失败:', error);
      throw error;
    }
  }

  // 获取用户通知
  async getUserNotifications(userId, limit = 50) {
    try {
      const notifications = await query(
        `SELECT id, title, content, summary, type, is_read, created_at
         FROM notifications 
         WHERE user_id = ? 
         ORDER BY created_at DESC 
         LIMIT ?`,
        [userId, limit]
      );

      return notifications;
    } catch (error) {
      console.error('获取用户通知失败:', error);
      throw error;
    }
  }

  // 标记通知为已读
  async markAsRead(userId, notificationId) {
    try {
      await query(
        'UPDATE notifications SET is_read = TRUE WHERE id = ? AND user_id = ?',
        [notificationId, userId]
      );
      return { success: true };
    } catch (error) {
      console.error('标记通知已读失败:', error);
      throw error;
    }
  }
}

module.exports = NotificationService;
